//
//  YMTextFieldVC.swift
//  swift_review
//
//  Created by Andrew on 2024/11/24.
//

import UIKit

class YMTextFieldVC: UIViewController, UITextFieldDelegate {
    
    private let textField: UITextField = {
           let tf = UITextField()
           tf.translatesAutoresizingMaskIntoConstraints = false
           tf.borderStyle = .roundedRect
           tf.placeholder = "请输入内容"
           return tf
       }()
       
       private let charCountLabel: UILabel = {
           let label = UILabel()
           label.translatesAutoresizingMaskIntoConstraints = false
           label.text = "0/20"
           label.textColor = .gray
           return label
       }()
       
       private let maxCharCount = 20 // 最大字数限制
       
       override func viewDidLoad() {
           super.viewDidLoad()
           view.backgroundColor = .white
           
           setupUI()
           
           // 设置代理
           textField.delegate = self
       }
       
       func setupUI() {
           view.addSubview(textField)
           view.addSubview(charCountLabel)
           
           NSLayoutConstraint.activate([
               // TextField 布局
               textField.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 50),
               textField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
               textField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
               textField.heightAnchor.constraint(equalToConstant: 40),
               
               // 字数标签布局
               charCountLabel.topAnchor.constraint(equalTo: textField.bottomAnchor, constant: 10),
               charCountLabel.trailingAnchor.constraint(equalTo: textField.trailingAnchor)
           ])
       }
       
       // MARK: - UITextFieldDelegate
       
       func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
           // 获取当前文本
           let currentText = textField.text ?? ""
           // 计算输入后的文本
           guard let textRange = Range(range, in: currentText) else { return false }
           let updatedText = currentText.replacingCharacters(in: textRange, with: string)
           
           // 更新字数标签
           charCountLabel.text = "\(updatedText.count)/\(maxCharCount)"
           
           // 限制输入字数
           return updatedText.count <= maxCharCount
       }
}
